﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Bricks.Component.Utils;
using Bricks.Business.Service.Helper.Logging;
using Bricks.Business.Service.Impl;
using Bricks.Business.Service;
using Bricks.Site.Models;
using Bricks.Business.Models.Account;
using Bricks.Component.Utils.Extensions;
using Bricks.Site.Models.Account;
using Bricks.Business.Service.CommonSupport;

namespace Bricks.Site.Web.Controllers
{
    [Export]
    public class AccountController : BaseController
    {
        #region 属性

        [Import]
        public IUserInfoService UserService { get; set; }

        [Import]
        public IOrgInfoService OrgInfoService { get; set; }

        [Import]
        public IUserOrgService UserOrgService { get; set; }

        #endregion

        #region 视图功能
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateVerifyCode(4);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateImageCodeByte(code);
            return File(bytes, @"image/jpeg");
        }

        /// <summary>
        /// 登录首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            UserInfoService.Logout();

            string returnUrl = Request.Params["returnUrl"];
            returnUrl = returnUrl ?? Url.Action("Index", "Main", new { area = "" });
            LoginView model = new LoginView
            {
#if DEBUG
                Account = "admin",
                Password = "123456",
#endif
                ReturnUrl = returnUrl
            };
            return View(model);
        }

        /// <summary>
        /// 登录按钮
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(LoginView model)
        {
            //ModelState.AddModelError 前台有Tips这个Key对应
            try
            {
                var code = Session["ValidateCode"] as string;
                //string msg;

                var codePass = true;
//#if !DEBUG
//                codePass = code == model.ViladateCode;
//#endif
                if (codePass)
                {
                    OperationResult result = UserService.Login(model);
                    //msg = result.Message ?? result.ResultType.ToDescription();
                    //if (result.ResultType == OperationResultType.Success)
                    //{
                    //    //return Redirect(model.ReturnUrl);
                    //    //return RedirectToAction("Index", "Main");
                    //    //Response.Redirect("/Main/Index");
                    //    //return View();
                    //    //return Json(result, "text/html");
                    //    return Content(JsonHelper.ToJson(result));  //若直接return Json，在IE下会提示是否保存json
                    //}
                    //else
                    //{
                    //    //ModelState.AddModelError("Tips", "用户名不存在或用户名/密码输入错误");
                    //    result = new OperationResult(OperationResultType.Error, "用户名或密码错误");
                    //    //return Json(result, "text/html");
                    //    return Content(JsonHelper.ToJson(result));
                    //}
                    //return Content(JsonHelper.ToJson(result));

                    return Json(result, "text/html");
                }
                else
                {
                    //msg = "验证码错误";
                    //ModelState.AddModelError("Tips", "验证码输入错误，请重新输入");

                    //model.ViladateCode = string.Empty;

                    OperationResult result = new OperationResult(OperationResultType.ParamError, "验证码输入错误");
                    //return Json(result, "text/html");
                    //return Content(JsonHelper.ToJson(result));

                    return Json(result, "text/html");
                }
                //ModelState.AddModelError("Tips", msg);
                //return View(model);
            }
            catch (Exception e)
            {
                //ModelState.AddModelError("Tips", e.Message);
                //return View(model);

                OperationResult result = new OperationResult(OperationResultType.Error, e.Message);
                //return Json(result, "text/html");
                //return Content(JsonHelper.ToJson(result));

                return Json(result, "text/html");
            }
        }

        /// <summary>
        /// 注销登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            string returnUrl = Request.Params["returnUrl"];
            returnUrl = returnUrl ?? Url.Action("Login", "Account", new { area = "" });
            if (User.Identity.IsAuthenticated)
            {
                UserService.Logout();
            }
            return Redirect(returnUrl);
        }

        /// <summary>
        /// 用户管理-首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewBag.PanelInfo = base.GetPanelInfo();
            ViewBag.ToolBarInfo = base.GetToolBarInfo() + "<span><input id=\"isContainsChildrenOrg\" type=\"checkbox\" onclick=\"Account.ReloadData()\" />显示下级机构</span>";
            return View();
        }

        /// <summary>
        /// 获取用户列表数据
        /// </summary>
        /// <param name="rows"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult GetDataList(string orgID = null, bool isContainsChildrenOrg = false, int rows = 20, int page = 1)
        {
            int total = 0;
            var query = UserService.GetUsersByOrgID(orgID.ToGuid(), isContainsChildrenOrg, rows, page, out total);
            var result = new { total = total, rows = query };
            return Json(result, "text/html");
        }

        /// <summary>
        /// 获取用户列表数据（不分页）
        /// </summary>
        /// <param name="orgID"></param>
        /// <returns></returns>
        public ActionResult GetDataListNoPage(string orgID = null)
        {
            var query = UserService.GetUsersByOrgIDNoPage(orgID.ToGuid());
            return Json(query, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 用户编辑界面
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="oldOrgID">用户记录里的OrgID（修改时使用）</param>
        /// <param name="newOrgID">新增时的OrgID（新增时使用）</param>
        /// <returns></returns>
        public ActionResult Edit(string id, string oldOrgID, string newOrgID)
        {
            UserView view = new UserView();
            //如果是编辑
            if (!String.IsNullOrEmpty(id))
            {
                Guid guidID = id.ToGuid();
                var record = UserService.Users.FirstOrDefault(m => m.ID == guidID);
                if (record != null)
                {
                    view = record.CopyTo<UserView>();
                    //view.Password = null;  //将Password赋值为空，如果检测到编辑状态，且密码为空，则不修改密码

                    if (!String.IsNullOrEmpty(oldOrgID))
                    {
                        Guid guidOrgID = oldOrgID.ToGuid();
                        var userOrg = UserOrgService.UserOrgs.FirstOrDefault(m => m.UserID == guidID && m.OrgID == guidOrgID);
                        if (userOrg != null)
                        {
                            view.IsPurviewAdmin = userOrg.IsPurviewAdmin;
                            view.IsHandoutAdmin = userOrg.IsHandoutAdmin;
                            view.IsFlowApprovalPerson = userOrg.IsFlowApprovalPerson;
                        }
                    }
                    //如果传入了newOrgID，则选中对应的机构
                    if (!String.IsNullOrEmpty(newOrgID))
                    {
                        view.OrgID = newOrgID.ToGuid();
                    }
                }
            }
            //如果是新增
            else
            {
                view.UserTypeNum = (int)UserType.Common;  //默认为普通用户
                view.OrgID = newOrgID.ToGuid();  //机构设置为选中的机构
            }

            //如果传入了orgID，则给机构ID赋值
            if (!String.IsNullOrEmpty(oldOrgID))
            {
                Guid guidOrgID = oldOrgID.ToGuid();
                view.OldOrgID = view.OrgID = guidOrgID;
            }
            return View(view);
        }

        /// <summary>
        /// 编辑响应
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(UserView view)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            ////判断密码输入是否一致
            //if (view.Password != view.ConfirmPassword)
            //{
            //    return Json(new OperationResult(OperationResultType.Warning, "两次密码不一致"));
            //}

            var record = UserService.Users.FirstOrDefault(m => m.ID == view.ID);
            //新增
            if (record == null)
            {
                //record = view.CopyTo<UserInfo>();
                //record.Password = EncryptHelper.ToMD5Salt(record.Password);  //加密
                if (UserInfoService.IsExistUserName(view, false))
                    result = new OperationResult(OperationResultType.Warning, string.Format("用户名[{0}]已存在，请重输",view.UserName));
                else
                    result = UserService.Add(view);
            }
            //修改
            else
            {
                //Modify By Luozx 2014-01-23：
                ////如果没填密码，则表示不修改密码
                //if (String.IsNullOrEmpty(view.Password))
                //{
                //string password = record.Password;  //记录原来的密码
                ////record = view.CopyTo<UserInfo>();
                ////record.Password = EncryptHelper.ToMD5Salt(password);  //加密
                ////view.Password = EncryptHelper.ToMD5Salt(password);  //加密
                //view.Password = password;  //加密
                //}
                //else
                //{
                //    //record = view.CopyTo<UserInfo>();
                //    view.Password = EncryptHelper.ToMD5Salt(view.Password);  //加密
                //}
                if (UserInfoService.IsExistUserName(view, true))
                    result = new OperationResult(OperationResultType.Warning, string.Format("用户名[{0}]已存在，请重输",view.UserName));
                else
                    result = UserService.Modify(view);
            }
            //return View();
            return Json(result, "text/html");
        }

        //[HttpPost]
        //public ActionResult ImportUser(string userID)
        //{
        //    ModelState.Clear();

        //    UserView view = new UserView();
        //    view.UserName = "abc";
        //    view.RealName = "abc";
        //    return View(view);
        //    //return View("Edit", view);
        //}

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(string id, string orgID)
        {
            Guid guidID = id.ToGuid();
            Guid guidOrgID = orgID.ToGuid();
            var exeResult = UserService.Delete(guidID, guidOrgID);
            return Json(exeResult);
        }

        /// <summary>
        /// 设置禁用或启用
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="isEnable">是否启用</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetEnable(string id, string isEnable)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            Guid guidID = id.ToGuid();
            var record = UserInfoService.Users.FirstOrDefault(m => m.ID == guidID);
            if (record != null)
            {
                record.IsDeleted = isEnable == "False";
                UserView view = new UserView();
                view = record.CopyTo<UserView>();
                result = UserInfoService.Modify(view);
                if (result.ResultType == OperationResultType.Success)
                    result.Message = (isEnable == "True" ? "启用" : "禁用") + "成功";
            }
            return Json(result);
            //return View();
        }

        /// <summary>
        /// 获取用户机构关系
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public ActionResult GetUserOrgs(string userID)
        {
            var queryData = OrgInfoService.Orgs.OrderBy(m => m.OrderNo).ToList();
            var data = from m in queryData
                       select new
                       {
                           iconCls = "icon-application",  //固定字段，作为treeField的图标
                           m.ID,
                           m.OrgName,
                           m.PID,
                           IsPurviewAdmin = false,
                           IsHandoutAdmin = false,
                           IsFlowApprovalPerson = false
                       };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 根据用户ID获取用户机构
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public ActionResult GetUserOrgsByUserID(string userID)
        {
            var orgs = UserInfoService.GetUserOrgsByUserID(userID.ToGuid());
            return Json(orgs, "text/html");
        }

        /// <summary>
        /// 引入现有用户
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportUser()
        {
            return View();
        }

        /// <summary>
        /// 引入现有用户（Post）
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportUserPost()
        {
            //ViewBag.SelectedUserID=
            //return Json(userID, JsonRequestBehavior.AllowGet);
            OperationResult result = new OperationResult(OperationResultType.Success);
            return Json(result, "text/html");
        }

        #region 从用户管理列表修改密码（暂时废除）
        ///// <summary>
        ///// 修改密码
        ///// </summary>
        ///// <param name="userID"></param>
        ///// <returns></returns>
        //public ActionResult ChangePassword(string userID)
        //{
        //    ChangePasswordView view = new ChangePasswordView();
        //    //如果没有传入userID，则说明是当前登录用户修改
        //    if (String.IsNullOrEmpty(userID))
        //        view.UserName = SystemData.Instance.CurrentUser.UserName;
        //    else
        //    {
        //        Guid guUserID = userID.ToGuid();
        //        var user = UserService.Users.FirstOrDefault(m => m.ID == guUserID);
        //        if (user != null)
        //            view.UserName = user.UserName;
        //    }
        //    return View(view);
        //}

        ///// <summary>
        ///// 修改密码（Post）
        ///// </summary>
        ///// <param name="view"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult ChangePasswordPost(ChangePasswordView view, string userID)
        //{
        //    OperationResult result = new OperationResult(OperationResultType.NoChanged, "无修改");
        //    var currentUser = SystemData.Instance.CurrentUser;
        //    //如果没有传入userID，则说明是当前登录用户修改
        //    if (String.IsNullOrEmpty(userID))
        //    {
        //        result = UserService.ChangePassword(currentUser.ID, view);
        //    }
        //    //如果传入userID，则说明是从用户管理列表进入的
        //    else
        //    {
        //        result = UserService.ChangePassword(userID.ToGuid(), view);
        //    }
        //    return Json(result, "text/html");
        //}
        #endregion

        #region 从主界面进入修改密码
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public ActionResult ChangePassword()
        {
            ChangePasswordView view = new ChangePasswordView();
            view.UserName = SystemData.Instance.CurrentUser.UserName;
            return View(view);
        }

        /// <summary>
        /// 修改密码（Post）
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChangePasswordPost(ChangePasswordView view, string userID)
        {
            OperationResult result = new OperationResult(OperationResultType.NoChanged, "无修改");
            var currentUser = SystemData.Instance.CurrentUser;
            result = UserService.ChangePassword(currentUser.ID, view);
            return Json(result, "text/html");
        }
        #endregion

        /// <summary>
        /// 重置密码（Post）
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ResetPassword(string id)
        {
            Guid guid = id.ToGuid();
            OperationResult result = UserService.ResetPassword(guid);
            return Json(result, "text/html");
        }

        #endregion
    }
}